﻿using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using UnityEngine;


public class SpellManager : MonoBehaviour 
{
	public GameObject fireBall;
	public List<SpellSlot> slots;
	public float[] coolDownTimes = new float[1];
	public float standardCoolDownTime = 5;
	[HideInInspector] public float[] nextCastTimes = new float [1];

	public PlayerController controller;

	private Vector3 targetPos;
	private Vector3 playerPos;
	public enum spellType
	{
		FireBall,
	}
	void Awake()
	{	
		for (int i = 0;i < coolDownTimes.Length ; i++)
		{
			nextCastTimes[i] = 0;
		} 
		foreach (SpellSlot slot in slots)
		{
			slot.spellManager = this;
		}
		
	}
	public void SetController()
	{
		controller = GameManager.instance.localPlayer.GetComponent<PlayerController>();
	}

	public enum spellKey
	{
		w,
		r,
		g,
	}

	private void getTargetPos()
	{
		Ray ray;
		RaycastHit hit;
		ray = Camera.main.ScreenPointToRay(Input.mousePosition);
		if (Physics.Raycast(ray, out hit))
		{
			targetPos = hit.point;
		}
		targetPos = new Vector3(targetPos.x,1,targetPos.z);
	}
	private void getPlayerPos()
	{
		playerPos = GameManager.instance.localPlayer.transform.position;
		playerPos = new Vector3(playerPos.x,1,playerPos.z);
	}
	private void getTargetCol()
	{

	}
	public void FireBall()
	{	
		if (controller == null)
		{
			SetController();
		}
		getTargetPos();
		getPlayerPos();
		Quaternion rot = Quaternion.LookRotation(targetPos-playerPos,new Vector3(0,1,0));
		controller.LookAt(targetPos);
		controller.GoTo(playerPos);
		PhotonNetwork.Instantiate(fireBall.name,playerPos+ 3F * (1/Vector3.Distance(targetPos,playerPos) * (targetPos-playerPos)),rot,0);
		SetNextCast(spellType.FireBall);
		
	}
	void SetNextCast(spellType spellEnum)
	{
		nextCastTimes[(int)spellEnum] = Time.time + coolDownTimes[(int)spellEnum] ;
	}
	public void Cast()
	{

	}

	void Update()
	{	
		if (Input.GetKeyDown(KeyCode.W) || Input.GetKeyDown(KeyCode.R) || Input.GetKeyDown(KeyCode.G))
		{
			int slotNum = 0;
			if (Input.GetKeyDown(KeyCode.W))
			{
				slotNum = (int)spellKey.w;
			}
			if (Input.GetKeyDown(KeyCode.R))
			{
				slotNum = (int)spellKey.r;
			}
			if (Input.GetKeyDown(KeyCode.G))
			{
				slotNum = (int)spellKey.g;
			}
			if (slots[slotNum].spell != null)
			{
				string spellName = slots[slotNum].spell.spellName;
				System.Type t = this.GetType();
				MethodInfo method = t.GetMethod(spellName);
				if (nextCastTimes[slots[slotNum].spellIndex] < Time.time)
				{
					method.Invoke(this,null);
				}
			}
			
		}
		
	
	}
}
